﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using DefaultScope;
using Microsoft.Synchronization.ClientServices.IsolatedStorage;
using System.Collections.ObjectModel;

namespace Klient
{
    public partial class LoginPage : PhoneApplicationPage
    {
        #region Dependency Property
        public static DependencyProperty AllEmployeesProperty = DependencyProperty.Register(
            "AllEmployees", typeof(ObservableCollection<Employees>), typeof(LoginPage), null);
        public ObservableCollection<Employees> AllEmployees
        {
            get
            {
                return (ObservableCollection<Employees>)GetValue(AllEmployeesProperty);
            }
            set
            {
                SetValue(AllEmployeesProperty, value);
            }
        }
        #endregion

        DefaultScopeOfflineContext loginContext;

        bool isCacheOpen = false;
        bool cacheBusy = false;

        // Constructor
        public LoginPage()
        {
            DataContext = this;

            loginContext = new DefaultScopeOfflineContext("login", new Uri("http://localhost:4000/DefaultScopeSyncService.svc/"));

            loginContext.CacheController.ControllerBehavior.SerializationFormat = Microsoft.Synchronization.ClientServices.SerializationFormat.ODataAtom;
            loginContext.CacheController.RefreshCompleted += new EventHandler<Microsoft.Synchronization.ClientServices.RefreshCompletedEventArgs>(CacheController_RefreshCompleted);
            loginContext.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(context_LoadCompleted);
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);

            InitializeComponent();

            isCacheOpen = true;
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            loginContext.Close();
            base.OnNavigatedFrom(e);
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (cacheBusy)
            {
                e.Cancel = true;
                return;
            }
            isCacheOpen = false;
            base.OnBackKeyPress(e);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (isCacheOpen)
            {
                progressBar.Visibility = Visibility.Collapsed;
                try
                {
                    loginContext.LoadAsync();
                }
                catch (ObjectDisposedException)
                {
                    /* ignore - sometimes happens that page is closed so quickly that context from which
                    * becomes disposed but it is not a problem, the page
                    * content do not interests us anyway after we left the page
                    */
                }
            }
        }

        void context_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            if (isCacheOpen)
            {
                Dispatcher.BeginInvoke(delegate
                {
                    progressBar.Visibility = Visibility.Collapsed;
                    AllEmployees = new ObservableCollection<Employees>(loginContext.EmployeesCollection);
                });
            }
        }

        void CacheController_RefreshCompleted(object sender, Microsoft.Synchronization.ClientServices.RefreshCompletedEventArgs e)
        {
            cacheBusy = false;
            if (isCacheOpen)
            {
                AllEmployees = new ObservableCollection<Employees>(loginContext.EmployeesCollection);
                progressBar.Visibility = Visibility.Collapsed;
                if (e.Error != null)
                    Dispatcher.BeginInvoke
                        (delegate
                        {
                            MessageBox.Show(e.Error.ToString());
                        }
                        );
            }
        }

        private void loginBtn_Click(object sender, RoutedEventArgs e)
        {
            Employees emp = (Employees)lista.SelectedItem;
            try
            {
                NavigationService.Navigate(new Uri("/Forms/EmployeePage.xaml?employeeID=" + emp.EmployeeID + "&employeeName=" + emp.LastName, UriKind.Relative));
            }
            catch (NullReferenceException exception)
            {
                //ignore a try to log in with null name
            }
        }

        private void refreshBtn_Click(object sender, RoutedEventArgs e)
        {
            if (isCacheOpen && !cacheBusy)
            {
                cacheBusy = true;
                loginContext.CacheController.RefreshAsync();
                progressBar.Visibility = Visibility.Visible;
            }
        }

    }
}